TomatoBreak = @TomatoBreak

Task = TomatoBreak.Task

class TaskController extends TomatoBreak.FormController

    constructor: ->

        super

        Task.bind 'error', (task, errors) => @showErrors errors
        Task.bind 'change', => @navigate '!/tasks', true

    change: (id) =>

        @id = id
        form = @form

        load = -> form.deserializeForm Task.find id

        if Task.count() then load() else Task.fetch -> load()

    submit: (event) ->

        event.preventDefault()

        attributes = @form.serializeForm()

        if attributes.dueAt
            # only parse the date if it is valid otherwise let the validation
            # handles it
            dueAt = (Date.parse attributes.dueAt)?.toString TomatoBreak.DATE_FORMAT
            attributes.dueAt = dueAt if dueAt?

        if @id?
            task = Task.find @id
            task.load attributes
        else
            task = new Task attributes

        task.save()

TomatoBreak.TaskController = TaskController